package org.dreamwork.jasmine2.parser;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-1-4
 * Time: 15:09:57
 */
public class CharsetDetector {
    private boolean found, ascii = true;
    private String charset = "utf-8";

    public CharsetDetector (InputStream in) throws IOException {
        detectCharset (in);
    }

    public CharsetDetector (URL url) throws IOException {
        detectCharset (url.openStream ());
    }

    private void detectCharset (InputStream in) throws IOException {
/*
        nsDetector detector = new nsDetector (nsDetector.ALL);
        detector.Init (new nsICharsetDetectionObserver() {
            public void Notify (String cs) {
                found = true;
                charset = cs;
            }
        });

        try {
            BufferedInputStream imp = new BufferedInputStream (in);
            byte[] buf = new byte[1024];
            int len;
            boolean done = false;
            while ((len = imp.read (buf, 0, buf.length)) != -1) {
                // Check if the stream is only ascii.
                if (ascii)
                    ascii = detector.isAscii (buf, len);
                // DoIt if non-ascii and not done yet.
                if (!ascii && !done)
                    done = detector.DoIt (buf, len, false);
            }
            detector.DataEnd ();

            if (ascii) {
                charset = "ASCII";
                found = true;
            }

            if (!found) {
                String[] charsets = detector.getProbableCharsets ();
                if (charsets != null && charsets.length > 0) charset = charsets [0];
                else charset = "UTF-8";
            }
        } finally {
            if (in != null) in.close ();
        }
*/
    }

    public String getCharset () {
        return charset;
    }
}